package com.jerry.boot.business.log;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jerry.boot.business.log.pojo.OprLogPojo;
import com.jerry.boot.core.base.SystemException;
import com.jerry.boot.core.mvc.PageBase;
import com.jerry.boot.core.mvc.PageReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OprLogServiceImpl extends ServiceImpl<OprLogMapper, OprLog> implements OprLogService {


    @Override
    public void writeLog(OprLogPojo oprLogPojo) {
        try {
            validateParam(oprLogPojo);
            OprLog oprLog = new OprLog();
            BeanUtil.copyProperties(oprLogPojo, oprLog);
            oprLog.setCreateTime(new Date());
            this.save(oprLog);
        } catch (Exception e) {
            log.error("write operate log error ...", e);
        }
    }

    @Override
    public PageBase<OprLogPojo> listPage(PageReq pageReq) {
        IPage<OprLog> reqPage = new Page<>(pageReq.getPage(), pageReq.getLimit());
        IPage<OprLog> resPage = this.page(reqPage);
        PageBase<OprLogPojo> result = new PageBase<>();
        result.setCode(0);
        result.setData(resPage.getRecords().stream().map(x -> {
            OprLogPojo oprLogPojo = new OprLogPojo();
            BeanUtil.copyProperties(x, oprLogPojo);
            return oprLogPojo;
        }).collect(Collectors.toList()));
        result.setCount(resPage.getTotal());
        return result;
    }

    private void validateParam(OprLogPojo oprLogPojo) {
        if (oprLogPojo == null) {
            throw new SystemException("oprLogPojo is null");
        }
        if (StrUtil.isBlank(oprLogPojo.getOprContent())) {
            throw new SystemException("oprLogPojo.getOprContent() is null");
        }
        if (StrUtil.isBlank(oprLogPojo.getOprApi())) {
            throw new SystemException("oprLogPojo.getOprApi() is null");
        }
        if (oprLogPojo.getOprId() == null) {
            throw new SystemException("oprLogPojo.getOprId() is null");
        }
        if (StrUtil.isBlank(oprLogPojo.getOprUsername())) {
            throw new SystemException("oprLogPojo.getOprUsername() is null");
        }
    }
}
